//------------------------------------------------------------------------------
// <copyright company="Telligent Systems">
//     Copyright (c) Telligent Systems Corporation.  All rights reserved.
// </copyright> 
//------------------------------------------------------------------------------

using System.Collections;
using CommunityServer.Components;

namespace CommunityServer.Galleries.Components
{
	/// <summary>
	/// Generates an XML feed for a photo gallery
	/// </summary>
	public class GalleryRssWriter : BaseGalleryRssWriter
	{
		protected PostCategory Category = null;

		public GalleryRssWriter(ArrayList posts, Gallery gallery, string baseUrl) : base(posts, gallery, baseUrl)
		{
			Category = null;
		}

		public GalleryRssWriter(ArrayList posts, Gallery gallery, string baseUrl, PostCategory category) : base(posts, gallery, baseUrl)
		{
			Category = category;
		}

		protected override bool AllowComments
		{
			get
			{
				return base.AllowComments && CurrentGallery.EnableCommentsDefault;
			}
		}

		protected override void PostComments(Post p)
		{
			base.PostComments (p);

			CSContext context = CSContext.Current;
			bool isAvailableToPublic = Permissions.ValidatePermissions(this.CurrentGallery, Permission.View, Users.GetAnonymousUser(true));
			
			if (Category != null)
				this.WriteElementString("comments", FormatUrl(GalleryUrls.Instance().ViewPicture(CurrentGallery.ApplicationKey,Category.CategoryID, p.PostID)));
			else
				this.WriteElementString("comments", FormatUrl(GalleryUrls.Instance().ViewPicture(CurrentGallery.ApplicationKey,p.PostID)));

			if (isAvailableToPublic)
				this.WriteElementString("wfw:commentRss", FormatUrl(GalleryUrls.Instance().CommentRss(CurrentGallery.ApplicationKey, p.PostID)));
			else
				this.WriteElementString("wfw:commentRss", FormatUrl(SiteUrls.FormatUrlWithUserNameToken(GalleryUrls.Instance().CommentRss(CurrentGallery.ApplicationKey, p.PostID), context.User, true)));

			if (CurrentGallery.EnableCommentsDefault && CurrentGallery.EnableRssCommentsDefault)
			{
				if (isAvailableToPublic)
					this.WriteElementString("wfw:comment", FormatUrl(GalleryUrls.Instance().RssComments(CurrentGallery.ApplicationKey, p.PostID)));
				else
					this.WriteElementString("wfw:comment", FormatUrl(SiteUrls.FormatUrlWithUserNameToken(GalleryUrls.Instance().RssComments(CurrentGallery.ApplicationKey, p.PostID), context.User, true)));
			}
		
		}


		protected override void WriteChannel()
		{
			if(Category != null)
				BuildChannel(GalleryUrls.Instance().ViewCategory(CurrentSection.ApplicationKey, Category.CategoryID) ,CurrentSection.Description, CurrentGallery.DefaultLanguage);
			else
				BuildChannel(GalleryUrls.Instance().ViewGallery(CurrentSection.ApplicationKey),CurrentSection.Description, CurrentGallery.DefaultLanguage);
		}

		protected override void PostBody(Post p)
		{
			GalleryPost gp = p as GalleryPost;
			if(gp == null)
				base.PostBody(p);
			else
			{

				base.WriteElementString("description",PostDescription(gp));

				WriteMedia(gp);
			}
         
		}

		protected string PostDescription(GalleryPost gp)
		{

			string desc = null;

			if(Category != null)
				desc = string.Format(@"<p><a href=""{0}"" >", Globals.FullPath(GalleryUrls.Instance().ViewPicture(CurrentSection.ApplicationKey, Category.CategoryID, gp)));
			else
				desc = string.Format(@"<p><a href=""{0}"" >", Globals.FullPath(GalleryUrls.Instance().ViewPicture(CurrentSection.ApplicationKey, gp)));

			desc += string.Format(@"<img src=""{0}"" alt=""{1}"" border=""0"" ></a></p>", Globals.FullPath(GalleryUrls.Instance().ThumbnailURL(gp)), gp.Subject);

			if(desc == null)
				desc = string.Format("<p>{0}</p>",gp.Subject) ;
			else
				desc += string.Format("<p>{0}</p>",gp.Subject) ;

			
			string hostPath = CSContext.Current.HostPath;
			if(gp.SyndicateExcerpt)
			{
				if(gp.HasExcerpt)
				{
					desc += gp.Excerpt;
				}
				else
				{
					desc += Formatter.RemoveHtml(gp.RenderedBody(PostTarget.Syndication)) ;
				}

				desc += string.Format("{0}...(<a href=\"{1}\">read more</a>)",desc,FormatUrl(BuildLink(gp)));
			}
			else
			{
				desc += gp.RenderedBody(PostTarget.Syndication);
			}
            
			if(desc.Length == 0)
				desc = null;
			
			return desc;
		}

		protected override void SetNamespaces()
		{
			base.SetNamespaces();
			this.WriteAttributeString("xmlns:media", "http://search.yahoo.com/mrss");
		}

		protected override void WritePostEnclosure(Post p)
		{
			GalleryPost gp = p as GalleryPost;
			//Using CS 1.1 Gallery PictureData
			//base.WriteRaw(string.Format(@"<enclosure url=""{0}"" length=""{1}"" type=""{2}"" />",  Globals.FullPath(GalleryUrls.Instance().PictureUrl(gp)), gp.Attachment.Length, gp.Attachment.ContentType ));
			this.WriteStartElement("enclosure");
			this.WriteAttributeString("url",Globals.FullPath(GalleryUrls.Instance().PictureUrl(gp)));
			this.WriteAttributeString("length", gp.Attachment.Length.ToString());
			this.WriteAttributeString("type", gp.Attachment.ContentType);
			this.WriteEndElement();
			
			//TODO: Move PictureData to standard PostAttacment for CS 1.2
			//if using the standard PostAttachement just override EnclosureUrl()
			//base.WriteRaw(string.Format(@"<enclosure url=""{0}"" length=""{1}"" type=""{2}"" />",  Globals.FullPath(GalleryUrls.Instance().PictureUrl(CurrentSection.ApplicationKey, p.PostID)), p.Attachment.Length, p.Attachment.ContentType ));
		}

		protected void WriteMedia(GalleryPost post)
		{
			//content
			//base.WriteRaw(string.Format(@"<media:content url=""{0}"" type=""{1}"" height=""{2}"" width=""{3}"" />",  Globals.FullPath(GalleryUrls.Instance().PictureUrl(post)),  "image/jpeg", post.Attachment.Height, post.Attachment.Width ));
			this.WriteStartElement("media:content");
			this.WriteAttributeString("url",Globals.FullPath(GalleryUrls.Instance().PictureUrl(post)));
			this.WriteAttributeString("type", "image/jpeg");
			this.WriteAttributeString("height",post.Attachment.Height.ToString());
			this.WriteAttributeString("width",post.Attachment.Width.ToString());
			this.WriteEndElement();

			// Subject is already HtmlEncoded in DB, so write raw
			this.WriteRaw(string.Format("<media:title>{0}</media:title>", post.Subject));
			
			//media:text
			//base.WriteRaw(string.Format(@"<media:text type=""html"">{0}</media:text>", PostDescription(post)));
			//base.WriteElementString("media:text",PostDescription(post));
			
			this.WriteStartElement("media:text");
			this.WriteAttributeString("type","html");
			this.WriteString(PostDescription(post));
			this.WriteEndElement();

			//<media:thumbnail 

			//TODO: we really need to store the resized image stats somewhere for easier retrieval
			GalleryImageSettings settings = ((Gallery)CurrentSection).GetThumbnailSettings();
			ImageHandling.GetMaintainedRatio(post, settings);
			//base.WriteRaw(string.Format(@"<media:thumbnail url=""{0}"" height=""{1}"" width=""{2}"" />", Globals.FullPath(GalleryUrls.Instance().ThumbnailURL(post) ), ((Gallery)CurrentSection).ThumbnailY, ((Gallery)CurrentSection).ThumbnailX));
			this.WriteStartElement("media:thumbnail");
			this.WriteAttributeString("url",Globals.FullPath(GalleryUrls.Instance().ThumbnailURL(post) ));
			this.WriteAttributeString("height", settings.Height.ToString());
			this.WriteAttributeString("width", settings.Width.ToString());
			this.WriteEndElement();

			//<media:credit role="photographer">
			this.WriteStartElement("media:credit");
			this.WriteAttributeString("role","photographer");
			this.WriteString(GetUserName(post));
			this.WriteEndElement();

			//<media:category scheme="urn:CS:tags">
			if(post.HasCategories)
			{
				this.WriteStartElement("media:category");
				foreach(string c in post.Categories)
				{
					this.WriteString(c);
					this.WriteString(" ");
				}
				this.WriteEndElement();
			}

		}

	}
}
